import { login_bak, getInfo_bak } from '@/api/user'
import { brand_login, brandGetInfo } from '@/api/brand'
import { getAgentTrees } from '@/api/agent'
import Layout from '@/layout'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  brand_id: '',
  brandTrees: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_BRANDID: (state, brand_id) => {
    state.brand_id = brand_id
  },
  SET_BRANDTREES: (state, brandTrees) => {
    state.brandTrees = brandTrees
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login_bak({ user_name: username.trim(), user_pass_word: password }).then(response => {
        // const { data } = response
        // console.log(response)
        commit('SET_TOKEN', 'h' + response.user_id)
        setToken('h' + response.user_id)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  brandLogin({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      brand_login({ brand_login_name: username.trim(), brand_login_pass_word: password }).then(response => {
        // const { data } = response
        console.log(response)
        if (response.code === 200) {
          commit('SET_TOKEN', 'b' + response.user_id)
          setToken('b' + response.user_id)
          resolve()
        } else if (response.code === 500) {
          Message({
            message: response.log,
            type: 'error',
            duration: 5 * 1000
          })
        } else if (response.code === 400) {
          Message({
            message: response.log,
            type: 'error',
            duration: 5 * 1000
          })
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const id = {
        id: state.token.slice(1)
      }
      if (state.token.slice(0, 1) === 'h') {
        // console.log(state.token.slice(0, 1))
        getInfo_bak(id).then(response => {
          const data = response
          console.log('123232', response)
          // if (!data) {
          //   reject('Verification failed, please Login again.')
          // }

          // const { roles, name, avatar, introduction } = data

          // // roles must be a non-empty array
          // if (!roles || roles.length <= 0) {
          //   reject('getInfo: roles must be a non-null array!')
          // }
          const brandTrees = {
            path: '/brand-trees',
            component: Layout,
            redirect: 'noRedirect',
            // alwaysShow: true,
            name: 'brand-trees',
            meta: {
              title: '品牌树',
              icon: 'tree',
              roles: ['admin', 'brand_admin']
            }
          }
          getAgentTrees().then(res => {
            // console.log(res)
            // console.log(res)
            const trees = []
            res.forEach(item => {
              const tree = {
                path: 'brand' + item.id,
                component: () => import('@/views/agent-system/trees/brands'),
                name: 'brand' + item.id,
                alwaysShow: true,
                redirect: 'noRedirect',
                meta: {
                  title: item.brand_name,
                  roles: ['admin', 'brand_admin']
                }
              }
              const levels = []
              item.level_content.forEach(i => {
                const level = {
                  path: 'content' + i.id,
                  component: () => import('@/views/agent-system/trees/brands/content'),
                  name: 'content' + i.id,
                  meta: {
                    title: i.level_name,
                    brandId: i.brand_id,
                    level: i.level_int
                  }
                }
                levels.push(level)
              })
              tree.children = levels
              trees.push(tree)
            })
            // console.log(trees)
            brandTrees.children = trees
            commit('SET_ROLES', data.roles)
            commit('SET_NAME', data.user_name)
            commit('SET_BRANDTREES', brandTrees)
            // commit('SET_AVATAR', avatar)
            // commit('SET_INTRODUCTION', introduction)
            resolve(data)
          })
        }).catch(error => {
          reject(error)
        })
      } else if (state.token.slice(0, 1) === 'b') {
        // console.log(state.token.slice(0, 1))
        const brandTrees = {
          path: '/brand-trees',
          component: Layout,
          redirect: 'noRedirect',
          // alwaysShow: true,
          name: 'brand-trees',
          meta: {
            title: '品牌树',
            icon: 'tree',
            roles: ['admin', 'brand_admin']
          }
        }
        brandGetInfo(id).then(response => {
          const data = response
          console.log('1111', data)
          // console.log(response)
          getAgentTrees({ brand_id: response.brand_id }).then(res => {
            // console.log(res)
            const trees = []
            res.forEach(item => {
              // console.log(item)
              const tree = {
                path: 'brand' + item.id,
                component: () => import('@/views/agent-system/trees/brands'),
                name: 'brand' + item.id,
                alwaysShow: true,
                redirect: 'noRedirect',
                meta: {
                  title: item.brand_name,
                  roles: ['admin', 'brand_admin']
                }
              }
              const levels = []
              item.level_content.forEach(i => {
                const level = {
                  path: 'content' + i.id,
                  component: () => import('@/views/agent-system/trees/brands/content'),
                  name: 'content' + i.id,
                  meta: {
                    title: i.level_name,
                    brandId: i.brand_id,
                    level: i.level_int
                  }
                }
                levels.push(level)
              })
              tree.children = levels
              trees.push(tree)
            })
            brandTrees.children = trees
            // console.log(brandTrees)
            commit('SET_BRANDTREES', brandTrees)
            commit('SET_ROLES', data.roles)
            commit('SET_NAME', data.user_name)
            commit('SET_BRANDID', data.brand_id)
            resolve(data)
          })
        }).catch(error => {
          reject(error)
        })
      }
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')
    // console.log(roles)
    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
